userDao = require("../dao/user")

exports.signin = function (req, res) {
    userName = req.body.name
    pwd = req.body.pwd
    email = req.body.email
    userDao.addUser(userName, email, pwd, res)
}

exports.login = function (req, res) {

    identifier = req.body.username
    pwd = req.body.password
    console.log("login", identifier, pwd)
    userDao.userMatch(identifier, pwd, res)
}

exports.handleUserMsg = function (body) {

    userId = body.userId
    friendId = body.peerId
    content = body.content
    state = body.state
    userDao.addUserMsg(userId, friendId, content, body.state)
}

exports.handleFriendsInfo = function (req, res) {
    userId = parseInt(req.query.userId)
    // { success: true, friendsList: rows }
    userDao.getFriendsInfo(userId, res)
        .then(function (friends) {
            userDao.getFriendsMsg(userId, res).then(msgs => {

                friendsList = []
                for (var i = 0; i < friends.length; i++) {
                    item = friends[i]
                    item.type = 'user'
                    item.unRead = 0
                    item.msgs = []
                    for (var j = 0; j < msgs.length; j++) {
                        if (item.groupId === msgs[j].friend_id) {
                            item.msgs.push({ isMe: true, content: msgs[j].message, time: msgs[j].ctime })
                        } else if (msgs[j].user_id === item.groupId) {
                            item.msgs.push({ isMe: false, content: msgs[j].message, time: msgs[j].ctime })
                        }
                    }
                    friendsList.push(item)
                }
                res.json({ success: true, friendsList: friendsList })
            })
        })
}
